package com.whjz.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.whjz.entity.UserParam;
import com.whjz.services.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author youkun
 * 验证token
 */
@Component
@Slf4j
public class TokenFilter extends ZuulFilter {


    @Autowired
    private UserService UserService;

    /**
     * pre 可以在请求被路由之前调用
     * route 在路由请求时被调用
     * post 在route和error过滤之后被调用
     * error 处理请求时发生错误时被调用
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";   //请求路由前调用
    }

    @Override
    public int filterOrder() {
        return 1;   //执行顺序 数字越大级别越低
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info("url:{}", request.getRequestURI());
        String param = null;
        JSONObject jsonObj = null;
        try {
            param = StreamUtils.copyToString((InputStream) request.getInputStream(), Charset.forName("UTF-8"));

            //log.info("校验token的请求参数的长度："+param.length());
            //判断是否包含用form提交的文件数据，有的话直接返回
            if (param.contains("form-data")) {
                return null;
            }

            //log.info("校验token的请求参数："+param);
            //GET请求没数据
            if (StringUtils.isEmpty(param)) {
                return null;
            }
            if ("mediaGate".equals(request.getParameter("sourceType"))) {
                //影像网关
            } else {
                jsonObj = JSONObject.parseObject(param);            //参数对象格式化
            }


        } catch (IOException e) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("code", "-1");
            map.put("msg", e.getMessage());
            ctx.setResponseBody(JSON.toJSONString(map));
            return null;
        }
        UserParam userParam = JSON.parseObject(param, UserParam.class);            //进行user对象格式化

        //log.info("token验证请求体{}"+ request.getRequestURI());
        if (!request.getRequestURI().contains("login") && !request.getRequestURI().contains("checkPersonByManegerLogin") && !request.getRequestURI().contains("sendNoteByMaster")) {
            //设置编码
            ctx.getResponse().setCharacterEncoding("UTF-8");
            log.info("\n=========>校验token  BEGIN.....");
            //校验token
            String sourceType = userParam.getSourceType();
            if (org.apache.commons.lang3.StringUtils.isBlank(sourceType)) {
                if (request.getRequestURI().contains("whjz-manage") || request.getRequestURI().contains("nmp-manage")) {
                    userParam.setSource(3);
                } else if (request.getRequestURI().contains("whjz-workstation") || request.getRequestURI().contains("nmp-workstation")) {
                    userParam.setSource(2);
                }

            } else {
                userParam.setSource(Integer.valueOf(sourceType));
            }
            Map<String, Object> result = UserService.checkToken(userParam);
            /** add by liweibin for (BUG)147登录超时机制修改  20181116 begin */
            if (result.get("code").equals("200")) {
                log.info("\n=========>token校验结果...比对成功.....");
                return null;
            } else {
                log.info("'\n==========>token校验结果...比对失败.....");
                jsonObj.put("code", result.get("code"));
                jsonObj.put("msg", result.get("msg"));
                jsonObj.put("data", null);        //add by liweibin for (TASK)95所有接口返回值除了业务数据还要添加token数据  20181127
                ctx.setSendZuulResponse(false);
                ctx.setResponseBody(JSON.toJSONString(jsonObj));
            }
        }


        //非登录校验的接口在登录时需更新TOKEN失效
//        UserService.checkToken(userParam);
        /** add by liweibin for (BUG)147登录超时机制修改  20181116 end */
        return null;
    }
}

